package cn.hn.tx.rebot.task.app;

import java.text.ParseException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.hn.comm.Tools;
import cn.hn.comm.exception.IExceptionService;
import cn.hn.tx.rebot.task.job.ITaskJob;
import cn.hn.tx.rebot.task.service.ITaskService;

import com.eic.core.spring.BeanFactoryUtil;

/**
 * 定时从数据库读取任务并执行
 * 
 * @author sh
 * 
 */
public class JobFromDBTask {

	private ITaskService taskService;
	// 异常记录
	private IExceptionService exceptionService;

	public void checkTaskTest() {

		ITaskJob taskJob = (ITaskJob) BeanFactoryUtil
				.getBean("TaskJob_CrawBlog_SinaEladies");
		taskJob.startJob();
	}

	/**
	 * 检查任务
	 */
	public void checkTask() {
		System.out.println("执行任务！");
		try {
			List<Map<String, Object>> listTask = taskService.getTaskList();
			Iterator<Map<String, Object>> iteraTask = listTask.iterator();
			while (iteraTask.hasNext()) {
				Map<String, Object> task = iteraTask.next();
				int en_able = (Integer) task.get("EN_ABLE");
				// 如果开启
				if (en_able == ITaskJob.TASK_ENABLE) {
					// nextTime
					long lNextTime = System.currentTimeMillis();
					// curTime
					long lCurTime = System.currentTimeMillis();

					lNextTime = ((Date) task.get("NEXT_TIME")).getTime();

					if (lCurTime >= lNextTime) {
						String implBean = (String) task.get("IMPL_BEAN");

						ITaskJob taskJob = (ITaskJob) BeanFactoryUtil
								.getBean(implBean);
						System.out.println(taskJob.toString());
						taskJob.startJob();

						// 更新下次时间 nextTime LAST_TIME
						Date lastTime = Tools.getCurDate(null);
						task.put("LAST_TIME", lastTime);
						int interval = (Integer) task.get("INTERVAL_TIME");
						interval *= 1000;
						long lNextTime_Write = lastTime.getTime() + interval;
						Date newNextTime = Tools.getDate(null, lNextTime_Write);

						task.put("NEXT_TIME", newNextTime);
						taskService.updateTask(task);
					}
				}
			}
		} catch (Exception e) {
			exceptionService.insertException(this.getClass().getName(), "checkTask()", e.toString());
		}
	}

	public ITaskService getTaskService() {
		return taskService;
	}

	public void setTaskService(ITaskService taskService) {
		this.taskService = taskService;
	}

	public IExceptionService getExceptionService() {
		return exceptionService;
	}

	public void setExceptionService(IExceptionService exceptionService) {
		this.exceptionService = exceptionService;
	}

}
